import http from "@/utils/request/httpRequest.ts";
import type {chunkType, UploadInitType, UploadListItemType, UploadPageListType} from "@/types/UploadType.ts";

// 检查文件是否上传
export const checkUpload = (data: chunkType) => http.post("file/upload/check", data);
// 初始化上传
export const initUpload = (data: UploadInitType) => http.post("file/upload/init", data);
// 分片上传
export const uploadChunk = (data: FormData) => {
    return http.post("file/upload/chunk", data, {
        headers: {
            "Content-Type": "multipart/form-data"
        },
    });
}
// 分片合并
export const mergeChunk = (data: chunkType) => http.post("file/upload/merge", data);
// 上传进度
// export const uploadProgress = (data: {
//     fileHash: string
// }) => http.post("file/upload/progress", data);

// 分页列表
export const uploadPageList = (data: UploadPageListType) => {
    return http.post<UploadListItemType[]>("file/upload/list", data);
}

// 文件下载
export const downloadFile = (data: {fileId: string}, range: {
    start: number,
    end: number,
    total: number
}) => {
    // 检查输入范围是否合法
    if (range.start < 0 || range.end < 0 || range.start > range.end) {
        throw new Error("范围设置错误：start 必须小于或等于 end，且不能为负数");
    }

    if (range.total < range.end) {
        throw new Error("范围设置错误：end 必须小于或等于 total");
    }

    return http.get("file/download/large", {
        params: data,
        headers: {
            'Range': `bytes=${range.start}-${range.end}`
        },
        responseType: 'blob'
    })
}